package org.Exm_1;


import java.io.*;
import java.math.BigDecimal;
import java.nio.file.*;
import java.time.LocalDateTime;
import java.util.*;

public class PurchaseSystem {
    private static final String PRODUCTS_CSV = "products.csv";
    private static final String PURCHASE_LOG = "purchase_log.txt";
    private List<Product> products = new ArrayList<>();

    public PurchaseSystem() {
        initializeFiles();
    }

    private void initializeFiles() {
        try {
            // 创建示例 products.csv 如果不存在
            if (!Files.exists(Paths.get(PRODUCTS_CSV))) {
                String sampleData = "1,苹果,5.99,100\n" +
                        "2,香蕉,3.50,150\n" +
                        "3,牛奶,8.00,50\n" +
                        "4,面包,12.50,30\n" +
                        "5,鸡蛋,15.00,200";
                Files.write(Paths.get(PRODUCTS_CSV), sampleData.getBytes());
                System.out.println("已创建示例 products.csv 文件");
            }

            // 创建空的 purchase_log.txt 如果不存在
            if (!Files.exists(Paths.get(PURCHASE_LOG))) {
                Files.createFile(Paths.get(PURCHASE_LOG));
            }
        } catch (IOException e) {
            System.err.println("初始化文件失败: " + e.getMessage());
        }
    }

    public void loadProducts() throws IOException {
        Path path = Paths.get(PRODUCTS_CSV);
        if (!Files.exists(path)) {
            throw new FileNotFoundException("找不到商品文件: " + path.toAbsolutePath());
        }

        List<String> lines = Files.readAllLines(path);
        products.clear(); // 清空现有商品

        for (String line : lines) {
            if (line.trim().isEmpty()) continue;

            String[] parts = line.split(",");
            if (parts.length < 4) {
                System.err.println("跳过无效行: " + line);
                continue;
            }

            try {
                int id = Integer.parseInt(parts[0].trim());
                String name = parts[1].trim();
                BigDecimal price = new BigDecimal(parts[2].trim());
                int stock = Integer.parseInt(parts[3].trim());

                if (price.compareTo(BigDecimal.ZERO) < 0) {
                    System.err.println("价格不能为负数，已设置为0: " + line);
                    price = BigDecimal.ZERO;
                }

                if (stock < 0) {
                    System.err.println("库存不能为负数，已设置为0: " + line);
                    stock = 0;
                }

                products.add(new Product(id, name, price, stock));
            } catch (Exception e) {
                System.err.println("解析失败: " + line + " - " + e.getMessage());
            }
        }
    }

    private Product findProduct(int id) {
        return products.stream()
                .filter(p -> p.getId() == id)
                .findFirst()
                .orElse(null);
    }

    public boolean makePurchase(String userId, int productId, int quantity) {
        if (quantity <= 0) {
            System.err.println("购买数量必须大于0");
            return false;
        }

        Product product = findProduct(productId);
        if (product == null) {
            System.err.println("商品不存在: " + productId);
            return false;
        }

        if (product.getStock() < quantity) {
            System.err.println("库存不足，当前库存: " + product.getStock());
            return false;
        }

        BigDecimal totalPrice = product.getPrice().multiply(new BigDecimal(quantity));
        product.setStock(product.getStock() - quantity);

        String record = String.format("%s,%d,%d,%s,%.2f",
                userId,
                productId,
                quantity,
                LocalDateTime.now(),
                totalPrice);

        boolean logSuccess = writeToPurchaseLog(record);

        if (logSuccess) {
            System.out.printf("购买成功！总价: ¥%.2f%n", totalPrice);
            return true;
        } else {
            product.setStock(product.getStock() + quantity);
            System.err.println("购买记录保存失败，已恢复库存");
            return false;
        }
    }

    private boolean writeToPurchaseLog(String record) {
        try (PrintWriter out = new PrintWriter(
                new FileWriter(PURCHASE_LOG, true))) {
            out.println(record);
            return true;
        } catch (IOException e) {
            System.err.println("写入购买日志失败: " + e.getMessage());
            return false;
        }
    }

    public void listProducts() {
        System.out.println("\n=== 商品列表 ===");
        System.out.println("ID | 名称           | 价格    | 库存");
        products.forEach(System.out::println);
    }
}